package com.shujia.thread_;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class ThiredThread implements Callable<String> {

    /*
    烧水泡茶
    1, 烧水
    2, 在烧水的时候准备茶具
    3, 茶具准备好了, 水也烧开了, 可以泡茶
    烧水需要2s, 准备茶具1s, 串行执行的话需要2s, 如果是并行的话只需要2s
     */
    public static void main(String[] args) {
        // 启动烧水的线程
        // FutureTask 实现了 RunnableFuture
        // RunnableFuture extends Runnable, Future<V>

        // FutureTask(Callable<V> callable)
//        ThiredThread t1 = new ThiredThread();
        FutureTask<String> task = new FutureTask(new ThiredThread());
        Thread thread = new Thread(task);
        thread.start();

        System.out.println("开始准备茶具");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("准备茶具结束");


        // 需要 thread 线程执行完毕, 才能执行下面的代码
        // join实现
//        try {
//            thread.join();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

        try {
            // 主线程会阻塞, 等待子线程执行完毕才能继续执行
            // 接收call方法的返回值
            String result = task.get();
            System.out.println(result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
            System.out.println("赶快关火!!!");
            return;
        }


        System.out.println("开始泡茶");


    }


    @Override
    public String call() throws Exception {
        System.out.println("开始烧水");
        Thread.sleep(2000);

        if (true) {
            throw new Exception("水烧干了..");
        }

        System.out.println("水烧开了");

        return "success";
    }
}
